import { useState, useEffect, useRef } from 'react';
import { invoke } from '@tauri-apps/api';
//import { listen } from '@tauri-apps/api/event';
import './App.css';

function App() {
  const [mediaUrl, setMediaUrl] = useState('');
  const videoRef = useRef<HTMLVideoElement | null>(null);

  useEffect(() => {
    const initPlayer = async () => {
      try {
        await invoke('init_player');
        console.log('Player initialized');
      } catch (error) {
        console.error('Failed to initialize player:', error);
      }
    };
    initPlayer();
  }, []);

  const handleFileSelect = async () => {
    try {
      const { open } = await import('@tauri-apps/api/dialog');
      const selected = await open({
        multiple: false,
        filters: [{ name: 'Video', extensions: ['mp4', 'avi', 'mkv', 'mov', 'wmv', 'webm'] }]
      });
      
      if (!selected || Array.isArray(selected)) {
        console.log('用户取消选择');
        return;
      }

      const fileUrl = await invoke<string>('get_file_url', { path: selected });
      
      console.log('Resolved file path:', {
        original: selected,
        resolved: await invoke('resolve_path', { path: selected })
      });
      
      setMediaUrl(fileUrl);
      console.log('Media loaded with URL:', fileUrl);
    } catch (error) {
      console.error('Failed to load media:', error);
    }
  };

  useEffect(() => {
    if (videoRef.current && mediaUrl) {
      videoRef.current.src = mediaUrl;
      videoRef.current.crossOrigin = "anonymous";
      videoRef.current.load();
      
      console.log('Video element state:', {
        src: videoRef.current.src,
        readyState: videoRef.current.readyState,
        networkState: videoRef.current.networkState
      });
    }
  }, [mediaUrl]);

  useEffect(() => {
    if (videoRef.current) {
      const video = videoRef.current;

      const handleLoadedData = () => {
        console.log('Video loaded data');
      };

      const handleCanPlay = () => {
        console.log('Video can play');
      };

      const handlePlay = () => {
        console.log('Video playing');
      };

      const handlePause = () => {
        console.log('Video paused');
      };

      video.addEventListener('loadeddata', handleLoadedData);
      video.addEventListener('canplay', handleCanPlay);
      video.addEventListener('play', handlePlay);
      video.addEventListener('pause', handlePause);

      return () => {
        video.removeEventListener('loadeddata', handleLoadedData);
        video.removeEventListener('canplay', handleCanPlay);
        video.removeEventListener('play', handlePlay);
        video.removeEventListener('pause', handlePause);
      };
    }
  }, [mediaUrl]);

  useEffect(() => {
    if (videoRef.current) {
      const canPlay = videoRef.current.canPlayType('video/mp4');
      console.log('Can play video/mp4:', canPlay);
    }
  }, [mediaUrl]);

  useEffect(() => {
    if (videoRef.current && mediaUrl) {
      videoRef.current.load(); 
      videoRef.current.onloadedmetadata = () => {
        console.log('Video duration:', videoRef.current?.duration);
        videoRef.current?.pause();
      };
    }
  }, [mediaUrl]);

  useEffect(() => {
    let unlisten: () => void;
    let isMounted = true;

    const setupListener = async () => {
      try {
        const { listen } = await import('@tauri-apps/api/event');
        const unlistenPromise = listen('menu-open-file', () => {
          if (isMounted) {
            handleFileSelect();
          }
        });
        
        unlisten = (await unlistenPromise) as () => void;
      } catch (error) {
        console.error('事件监听失败:', error);
      }
    };

    setupListener();

    return () => {
      isMounted = false;
      unlisten?.();
    };
  }, []);

  return (
    <div className="app-container">
      <div className="player-container">
        {mediaUrl && (
          <div className="media-player-container">
            <video
              ref={videoRef}
              src={mediaUrl}
              controls
              preload="metadata"
              controlsList="nodownload"
              disablePictureInPicture
              playsInline
              crossOrigin="anonymous"
              style={{ 
                width: '100%', 
                height: '100%',
                backgroundColor: '#000',
                objectFit: 'contain'
              }}
              onError={(e) => {
                const video = e.currentTarget;
                console.error('Video error details:', {
                  code: video.error?.code,
                  message: video.error?.message,
                  mediaError: video.error
                });
              }}
            />
          </div>
        )}
      </div>
    </div>
  );
}

export default App;
